package com.tianmu.connector.server.tablemeta;

import com.tianmu.connector.server.BinlogConnectorException;
import com.tianmu.connector.server.config.SyncConfig;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author tianmu
 */
public class TableMetaFactory {
    SyncConfig syncConfig;

    public TableMetaFactory(SyncConfig syncConfig) {
        this.syncConfig = syncConfig;
    }

    //缓存tableId信息
    private final Map<Long, TableMetaEntity> tableMetaEntityIdMap = new HashMap<>();

    public void getTableMetaEntity(Long tableId, String dbName, String tableName) throws BinlogConnectorException {
        Connection connection = null;
        try {
            if (tableMetaEntityIdMap.get(tableId) != null) {
                return;
            }
            String url = "jdbc:mysql://" + syncConfig.getHost() + ":" + syncConfig.getPort() + "/" + dbName;
            connection = DriverManager.getConnection(url, syncConfig.getUserName(), syncConfig.getPassword());
            DatabaseMetaData dbmd = connection.getMetaData();
            ResultSet rs = dbmd.getColumns(dbName, dbName, tableName, null);
            TableMetaEntity tableMetaEntity = new TableMetaEntity();
            tableMetaEntity.setTableId(tableId);
            tableMetaEntity.setDbName(dbName);
            tableMetaEntity.setTableName(tableName);
            while (rs.next()) {
                TableMetaEntity.ColumnMetaData columnMetaData = new TableMetaEntity.ColumnMetaData();
                String colName = rs.getString("COLUMN_NAME");
                columnMetaData.setName(colName);
                String dbType = rs.getString("TYPE_NAME");
                columnMetaData.setType(dbType);
                tableMetaEntity.getColumnMetaDataList().add(columnMetaData);
            }
            tableMetaEntityIdMap.put(tableId, tableMetaEntity);
        } catch (SQLException e) {
            throw new BinlogConnectorException(e.getCause());
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException ignored) {
                }
            }
        }
    }

    /**
     * 根据tableId获取表元数据
     * @param tableId tableId
     * @return 表元数据
     */
    public TableMetaEntity getTableMetaEntity(Long tableId) {
        return tableMetaEntityIdMap.get(tableId);
    }
}
